package com.manager.api;

import com.manager.common.constant.SystemConstant;
import com.manager.common.job.GetDockerContainerLogsInfoThread;
import com.manager.common.ssh.RemoteExecuteLinuxCommandTools;
import com.manager.common.tcp.client.TcpClient;
import com.manager.common.tcp.decode.impl.BusinessDecode;
import com.manager.common.tcp.encode.impl.BusinessEncode;
import com.manager.common.utils.DataTools;
import com.manager.common.utils.DateTools;
import com.manager.common.utils.ResultVO;
import com.manager.model.DockerLogs;
import com.manager.model.DockerTop;
import com.manager.model.LinuxTcpInfo;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api")
public class ApiController {

    @Value("${linux.ssh.ip}")
    private String ip;

    @Value("${linux.ssh.port}")
    private Integer port;

    @Value("${linux.ssh.password}")
    private String password;

    @Value("${linux.ssh.user.name}")
    private String userName;

    @RequestMapping("/getDockerContainerInfo")
    public ResultVO getDockerContainerInfo() {
        try{
            return ResultVO.success(DataTools.getContainerStats());
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultVO.failed();
    }

    @RequestMapping("/getDockerContainerInfoById")
    public ResultVO getDockerContainerInfoById(@RequestBody  String containerIdJson) {
        try{
            String containerId = JSONObject.fromObject(containerIdJson).get("containerId").toString();
            return ResultVO.success(DataTools.getContainerStatsById(containerId));
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultVO.failed();
    }

    @RequestMapping("/getMonitorInfoByContainerId")
    public ResultVO getMonitorInfoByContainerId(@RequestBody  String containerIdJson) {
        try{
            String containerId = JSONObject.fromObject(containerIdJson).get("containerId").toString();
            if(!DataTools.existDockerLogs(containerId)){
                GetDockerContainerLogsInfoThread dockerContainerLogsInfoThread = new GetDockerContainerLogsInfoThread( ip,  port,  password,  userName, containerId);
                DataTools.executorService.submit(dockerContainerLogsInfoThread);
            }
            return ResultVO.success(DataTools.getDockerContainerLog(containerId));
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultVO.failed();
    }

    @RequestMapping("/getDockerContainerTop")
    public ResultVO getDockerContainerTop(@RequestBody  String containerIdJson) {
        try{
            String containerId = JSONObject.fromObject(containerIdJson).get("containerId").toString();
            String command = " docker top " + containerId;
            List<String> out = new ArrayList<>();
            boolean hasSuccess = RemoteExecuteLinuxCommandTools.excuteRemoteSSH(ip,userName,password,port,out,command);
            if(!hasSuccess){
                return ResultVO.failed(out);
            }
            List<DockerTop> dockerTopList = new ArrayList<>();
            for(int i = 1; i < out.size(); i++){
                String[] arr = out.get(i).split(" ");
                List<String> filteredList = Arrays.stream(arr)
                        .filter(s -> s != null && !s.isEmpty())
                        .collect(Collectors.toList());
                String[] resultArray = filteredList.toArray(new String[0]);
                String cmd = "";
                for(int j = 7;j < resultArray.length;j++){
                    cmd += resultArray[j] + " ";
                }
                DockerTop dockerTop = new DockerTop(resultArray[0],resultArray[1],resultArray[2],resultArray[3],resultArray[4],resultArray[5],resultArray[6],cmd);
                dockerTopList.add(dockerTop);
            }
            return ResultVO.success(dockerTopList);
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultVO.failed();
    }

    @RequestMapping("/getLinuxBaseInfo")
    public ResultVO getLinuxBaseInfo() {
        try{
            return ResultVO.success(DataTools.getLinuxBaseMonitorList());
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultVO.failed();
    }

    @RequestMapping("/saveContainerLogsByContainerId")
    public ResultVO saveContainerLogsByContainerId(@RequestBody  String containerIdJson) {
        try{
            JSONObject jsonObject = JSONObject.fromObject(containerIdJson);
            String containerId = jsonObject.getString("containerId");
            String tempSavePath = jsonObject.getString("tempSavePath");
            List<String> out = new ArrayList<>();
            String fileName = tempSavePath + "/" + containerId + "/" + DateTools.getCurrentDateString("yyyyMMddHHmmssSSS") + ".log";
            String mkdirCommand = "mkdir -p  " + tempSavePath + "/" + containerId;
            String command = "docker logs "+containerId+" > " + fileName;
            boolean hasSuccess = RemoteExecuteLinuxCommandTools.excuteRemoteSSH(ip,userName,password,port,out,mkdirCommand,command);
            if(hasSuccess){
                JSONArray  jsonArray = new JSONArray();
                jsonArray.add(fileName);
                return ResultVO.success(jsonArray);
            }
            return ResultVO.failed(out);
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultVO.failed();
    }

    @RequestMapping("/getLinuxTcpInfo")
    public ResultVO getLinuxTcpInfo() {
        try{
            List<LinuxTcpInfo> list = DataTools.getCacheLinuxMonitor(SystemConstant.LINUX_TCP_MONITOR_LIST);
            return ResultVO.success(list);
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultVO.failed();
    }

    @RequestMapping("/issueInstructions")
    public ResultVO issueInstructions(@RequestBody  String instructions) {
      try {
          JSONObject jsonObject = JSONObject.fromObject(instructions);
          int code = jsonObject.getInt("code");
          String content = jsonObject.getString("content");
          System.out.println("指令数据：" + instructions);
          BusinessEncode businessDecode = new BusinessEncode(code);
          TcpClient.getInstance().send(businessDecode.encode(content));
      }catch (Exception e){
          e.printStackTrace();
      }
      return ResultVO.failed("指令格式错误!");
    }
}
